home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: thinkage.on.ca!atbowler
- From: atbowler@thinkage.on.ca (Alan Bowler)
- Subject: Re: Random numbers...?
- Message-ID: <DLApIv.8IA@thinkage.on.ca>
- Sender: news@thinkage.on.ca
- Organization: Thinkage Ltd.
- References: <30DDBEB1.4C42@aruba.ccit.arizona.edu> <DKDz1v.736@eskimo.com> <4d2c6o$h7l@maureen.teleport.com>
- Date: Tue, 16 Jan 1996 22:37:43 GMT
-
- In article <4d2c6o$h7l@maureen.teleport.com> muse@teleport.com (Andrew T Millard) writes:
- >mAg (mag@eskimo.com) wrote:
- >: In article <30DDBEB1.4C42@aruba.ccit.arizona.edu> (Sun, 24 Dec 1995 13:57:21 -0700),
- >: vaughn@aruba.ccit.arizona.edu says :
- >: >
- >: >Hello,
- >: >Thanks to those who helped me with my last question on
- >: >cache-flushing. I realize I'm showing my newness to C by even asking
- >: >this, but I need to get some code that will simply generate a random
- >: >integer from 0 to 9. Specifically, I want to generate a string of
- >: >four random digits. I keep generating numbers that look suspiciously
- >: >non-random somehow (seeding the random number generator with the
- >: >current time). Any ideas?
- >: >
- >: >Thanks,
- >: >Bill Vaughn
- >
- >Bill, this routine should do fine:
- >
- >#include <stdio.h>
- >#include <math.h>
-
- You want "#include <stdlib.h>" to define rand(), srand() and RAND_MAX
-
- >
- >void main(void)
-
- NEVER define "main" as returning "void". This is always incorrect
- even if some implementations don't blow up.
-
- >{
- > int iCount, digit[4];
- >
- > srand(time()); /* Seeds random numbers */
-
- But you need "#include <time.h>" to do this, and time()
- needs the argument NULL to be used like this.
-
- > for(iCount = 0; iCount <= 3; iCount++)
- > {
- > digit[iCount] = abs(rand() % 10);
- ^^^
- "rand" always returns a positive value so you don't need to
- call "abs" on the result.
- > }
- >}
- >
-
- Is is common for rand() to be implemented with a very fast algorithm
- that does not work well with "%" to select the lower bits. Instead
- you want
-
- (int) (rand() /(((double)RAND_MAX + 1) / 10)
-
- This is a little cumbersome so the following is easier and
- usually faster.
-
- while (10 <= (rval = rand()/(RAND_MAX/10));
- digit[iCount] = rval;
-
- The "while" will normally only execute once, but very occasionally
- rand()/(RAND_MAX/10)
- will produce the value 10. Putting it in the "while" just discards
- those few cases.
- )
-